/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// Remote Object
function RemoteObject(name) {
    this.name = name;
    this.listener = null;
    this.getAction = function(actionName) {
        return new RemoteAction(this.name, actionName, this.listener);
    };
}

// Remote action
function RemoteAction(serviceName, actionName, listener)
{
    this.serviceName = serviceName;
    this.actionName = actionName;
    this.onLoad = null;
    this.invoke = invokeRemoteAction;
    this.attachFile = false;
    this.progressUpdate = false;
    this.listener = listener;

    this.setHandler = function(handler) {
        this.onLoad = handler;
        return this;
    };

    this.attach = function(file) {
        this.attachFile = file;
        return this;
    };

}
;

// invoke the remote action
function invokeRemoteAction()
{
    var args = JSON.stringify(arguments);
    var xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.open("POST", "gateway.php", true);
    xmlHttpRequest.remoteAction = this;
    xmlHttpRequest.onload = handleOnLoad;

    if (this.progressUpdate) {
        xmlHttpRequest.upload.onprogress = this.progressUpdate;
    }

    var formData = new FormData();
    formData.append('service', this.serviceName);
    formData.append('action', this.actionName);
    formData.append('json', true);
    formData.append('json_arguments', args);

    if (this.attachFile) {
        formData.append('file', this.attachFile);
    }

    xmlHttpRequest.send(formData);
}
;

function handleOnLoad()
{
    if (this.remoteAction.listener && this.remoteAction.listener[this.remoteAction.actionName + "Loaded"]) {
        var data = JSON.parse(this.responseText);
        this.remoteAction.listener[this.remoteAction.actionName + "Loaded"](data.data, this.remoteAction);
    }
    
    if (this.remoteAction.onLoad) {
        var data = JSON.parse(this.responseText);
        this.remoteAction.onLoad(data.data);
    }
}
    